package com.three.iot.service.impl;

import com.three.iot.api.LoginInfoService;
import com.three.iot.api.SysRoleResourceService;
import com.three.iot.api.SysUserRoleService;
import com.three.iot.api.UserDeviceService;
import com.three.iot.commons.dto.SysRoleResourceResultDto;
import com.three.iot.commons.dto.SysUserRoleResultDto;
import com.three.iot.commons.dto.UserCreateDto;
import com.three.iot.commons.dto.UserModiPassDto;
import com.three.iot.commons.enums.IfAdminEnum;
import com.three.iot.commons.enums.Result;
import com.three.iot.commons.enums.ResultCode;
import com.three.iot.commons.enums.StatusEnum;
import com.three.iot.commons.po.UserInfo;
import com.three.iot.commons.po.UserPermit;
import com.three.iot.commons.utils.DateUtil;
import com.three.iot.commons.utils.MD5Util;
import com.three.iot.commons.utils.ThreeDESUtil;
import com.three.iot.jdbc.mapper.SysUserMapper;
import com.three.iot.jdbc.model.SysUser;
import com.three.iot.service.core.LoginCoreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户登录表 服务实现类
 * </p>
 *
 * @author luiz
 * @since 2019-04-03
 */
@Service
public class LoginInfoServiceImpl implements LoginInfoService {
    private static final Logger logger = LoggerFactory.getLogger(LoginInfoServiceImpl.class);
    @Resource
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleResourceService sysRoleResourceService;
    @Resource
    private LoginCoreService loginCoreService;


    @Override
    public Result findByLoginNo(String loginNo) {
        SysUser sysUser = sysUserMapper.selectByIndex(loginNo);
        if (sysUser == null) {
            return Result.newError(ResultCode.USER_NOT_EXISTS);
        }
        UserInfo userInfo = buildResultInfo(sysUser);
        return Result.newSuccess(userInfo);
    }

    @Override
    public Result doLogin(String loginNo, String loginPass) {
        String encryptPass = ThreeDESUtil.encryptToHex(loginPass);
        SysUser tkUser = sysUserMapper.selectByIndex(loginNo);
        if (tkUser == null) {
            return Result.newError(ResultCode.USER_NOT_EXISTS);
        }
        String userNo = tkUser.getUserNo();
        if (StatusEnum.VALID.getCode() != tkUser.getStatus()) {
            return Result.newError(ResultCode.USER_HAS_LOCK);
        }
        if (!tkUser.getLoginPass().equals(encryptPass)) {
            return Result.newError(ResultCode.USERNAME_OR_PASS_ERR);
        }
        UserInfo userInfo = buildResultInfo(tkUser);
        //登录成功，则修改登录信息
        // 开始进入shiro的认证流程
        //ShiroUtils.login(token);
        return Result.newSuccess(userInfo);
    }

    /* @Transactional
   public Result doRegister(UserRegisterDto userRegisterDto) {
        List<TkUser> tkUsers=tkUserMapper.selectByCond(userRegisterDto);
        if(tkUsers!=null && tkUsers.size()>=1){
            return Result.newError(ResultCode.USER_HAS_EXISTS);
        }
        //创建成功，发送邮件确认 todo 待添加
        return loginCoreService.doRegister(userRegisterDto);
    }*/

    /**
     * 修改密码
     *
     * @param userModiPassDto
     * @return
     */
    @Override
    public Result doModiPass(UserModiPassDto userModiPassDto) {
        SysUser sysUser = sysUserMapper.selectByIndex(userModiPassDto.getLoginNo());
        if (sysUser == null) {
            return Result.newError(ResultCode.USER_NOT_EXISTS);
        }
        String signPass = ThreeDESUtil.encryptToHex(userModiPassDto.getOldPass());
        if (!sysUser.getLoginPass().equals(signPass)) {
            return Result.newError(ResultCode.USER_OLD_PASS_ERROR);
        }
        if (!userModiPassDto.getPasswordNew1().equals(userModiPassDto.getPasswordNew2())) {
            return Result.newError(ResultCode.USER_PASS_NOT_EQUAL);
        }
        String pass1 = userModiPassDto.getPasswordNew1();
        if (pass1.contains(userModiPassDto.getLoginNo())) {
            return Result.newError(ResultCode.PASS_CANNOT_CONTAINS_ACCOUNT);
        }
        String signPass1 = ThreeDESUtil.encryptToHex(pass1);
        sysUser.setLoginPass(signPass1);
        sysUser.setModiTime(new Date());
        sysUserMapper.updateByPrimaryKeySelective(sysUser);
        return Result.newSuccess();
    }




    private UserInfo buildResultInfo(SysUser sysUser) {
        UserInfo userInfo = new UserInfo();
        String userNo = sysUser.getUserNo();
        BeanUtils.copyProperties(sysUser, userInfo);
        userInfo.setCreateTime(DateUtil.getDateTimeFormat(sysUser.getCreateTime()));
        userInfo.setModiTime(DateUtil.getDateTimeFormat(sysUser.getModiTime()));
        userInfo.setStatus(sysUser.getStatus().toString());
        userInfo.setStatusName(StatusEnum.getNameByCode(sysUser.getStatus()));
        userInfo.setIfAdmin(sysUser.getIfAdmin());
        userInfo.setIfAdminName(IfAdminEnum.getNameByCode(sysUser.getIfAdmin()));
        Result<List<SysUserRoleResultDto>> sysUserRoleResult = sysUserRoleService.findByUserNo(userNo);
        List<SysUserRoleResultDto> sysUserRoleResultDtos = sysUserRoleResult.getData();
        List<String> groupList = new ArrayList<>();
        if (sysUserRoleResult.isSuccess() && sysUserRoleResultDtos != null && sysUserRoleResultDtos.size() >= 1) {
            for (SysUserRoleResultDto sysUserRoleResultDto : sysUserRoleResultDtos) {
                groupList.add(sysUserRoleResultDto.getRoleCode());
            }
        }
        userInfo.setUerGroups(groupList);
        Result<List<SysRoleResourceResultDto>> sysRoleResourceResult = sysRoleResourceService.findByUserNo(userNo);
        List<SysRoleResourceResultDto> sysRoleResourceResultDtos = sysRoleResourceResult.getData();
        List<UserPermit> userPermits = new ArrayList<>();
        if (sysRoleResourceResult.isSuccess() && sysRoleResourceResultDtos != null && sysRoleResourceResultDtos.size() >= 1) {
            for (SysRoleResourceResultDto sysRoleResourceResultDto : sysRoleResourceResultDtos) {
                UserPermit userPermit = new UserPermit();
                userPermit.setGroupNo(sysRoleResourceResultDto.getRoleCode());
                userPermit.setSourceNo(sysRoleResourceResultDto.getSourceNo());
                userPermit.setPSourceNo(sysRoleResourceResultDto.getPId());
                userPermit.setSourceName(sysRoleResourceResultDto.getSourceName());
                userPermit.setReqUrl(sysRoleResourceResultDto.getReqUrl());
                userPermit.setSourceIcon(sysRoleResourceResultDto.getSourceIcon());
                userPermit.setSourceLevel(sysRoleResourceResultDto.getSourceLevel());
                userPermit.setUserNo(userNo);
                userPermits.add(userPermit);
            }
        }
        userInfo.setUserPermits(userPermits);
        return userInfo;
    }


}
